package service

import (
	"fitness/internal/dao"
	"fitness/internal/entity/system"
	"fitness/pkg/utils/R"
	"github.com/gin-gonic/gin"
	"go.uber.org/zap"
	"net/http"
	"strconv"
)

type DeptService struct {
	DeptDao *dao.DeptDao
	Log     *zap.Logger
}

func NewDeptService(DeptDao *dao.DeptDao,
	Log *zap.Logger) *DeptService {
	return &DeptService{
		DeptDao: DeptDao,
		Log:     Log,
	}
}

func (s *DeptService) GetDepts(c *gin.Context) {
	var deptQuery system.DeptQuery
	err := c.ShouldBindQuery(&deptQuery)
	if err != nil {
		c.JSON(http.StatusOK, R.ReturnFailMsg(err.Error()))
		return
	}

	list, err := s.DeptDao.GetDepts(deptQuery)
	if err != nil {
		c.JSON(http.StatusOK, R.ReturnFailMsg(err.Error()))
		return
	}
	c.JSON(http.StatusOK, R.ReturnSuccess(list))
}

func (s *DeptService) DeptOptions(c *gin.Context) {
	options := s.DeptDao.ListDeptOptions()
	c.JSON(http.StatusOK, R.ReturnSuccess(options))
}

func (s *DeptService) GetDeptForm(c *gin.Context) {
	detpIdStr := c.Param("deptId")
	// 尝试将字符串转换为整数
	deptId, err := strconv.ParseUint(detpIdStr, 10, 64)
	if err != nil {
		// 如果转换失败，返回错误响应
		c.JSON(http.StatusOK, "Invalid ID")
		return
	}
	form, err := s.DeptDao.GetDeptForm(deptId)
	if err != nil {
		c.JSON(http.StatusOK, R.ReturnFailMsg(err.Error()))
		return
	}
	c.JSON(http.StatusOK, R.ReturnSuccess(form))
}

func (s *DeptService) SaveDept(c *gin.Context) {
	var deptForm system.DeptForm
	err := c.ShouldBindJSON(&deptForm)
	if err != nil {
		c.JSON(http.StatusOK, R.ReturnFailMsg("修改部门信息失败"))
		return
	}

	result, err := s.DeptDao.SaveDept(deptForm)
	if err != nil {
		c.JSON(http.StatusOK, R.ReturnFailMsg(err.Error()))
		return
	}
	c.JSON(http.StatusOK, R.ReturnSuccess(result))
}

func (s *DeptService) UpdateDept(c *gin.Context) {
	var deptForm system.DeptForm
	err := c.ShouldBindJSON(&deptForm)
	if err != nil {
		c.JSON(http.StatusOK, R.ReturnFailMsg("修改部门信息失败"))
		return
	}
	if deptForm.ID == deptForm.ParentId {
		c.JSON(http.StatusOK, R.ReturnFailMsg("不可以自身作为父级部门"))
		return
	}

	result, err := s.DeptDao.UpdateDept(deptForm)
	if err != nil {
		c.JSON(http.StatusOK, R.ReturnFailMsg(err.Error()))
		return
	}
	c.JSON(http.StatusOK, R.ReturnSuccess(result))
}

func (s *DeptService) DeleteDepts(c *gin.Context) {
	idStr := c.Param("ids")
	b, err := s.DeptDao.DeleteDepts(idStr)
	if err != nil {
		c.JSON(http.StatusOK, R.ReturnFailMsg(err.Error()))
		return
	}
	c.JSON(http.StatusOK, R.ReturnSuccess(b))
}
